<template>
  <div class="feedback-manage">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h2>反馈管理</h2>
        <p class="header-desc">查看和管理活动反馈信息</p>
      </div>
      <div class="header-stats">
        <el-tag type="info" size="large">总计 {{ pagination.total }} 条反馈</el-tag>
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="searchForm" inline>
        <el-form-item label="学生姓名">
          <el-input
            v-model="searchForm.sname"
            placeholder="请输入学生姓名"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="活动名称">
          <el-input
            v-model="searchForm.aname"
            placeholder="请输入活动名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="反馈内容">
          <el-input
            v-model="searchForm.feedbackInfo"
            placeholder="请输入反馈内容"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch" :loading="loading">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="hover">
      <div class="table-wrapper">
        <el-table
          v-loading="loading"
          :data="feedbackList"
          stripe
          border
          style="width: 100%"
          :height="tableHeight"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          
          <el-table-column prop="sname" label="学生姓名" min-width="120" show-overflow-tooltip>
            <template #default="{ row }">
              <div class="student-name">
                <el-icon class="name-icon"><User /></el-icon>
                <el-text class="name-text" type="primary">{{ row.sname }}</el-text>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="aname" label="活动名称" min-width="150" show-overflow-tooltip>
            <template #default="{ row }">
              <div class="activity-name">
                <el-icon class="activity-icon"><Calendar /></el-icon>
                <el-text class="activity-text">{{ row.aname }}</el-text>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="ename" label="发布人" width="120" align="center" />

          <el-table-column prop="feedbackInfo" label="反馈信息" min-width="250" show-overflow-tooltip>
            <template #default="{ row }">
              <div class="feedback-content">
                <el-text class="feedback-text" truncated>{{ row.feedbackInfo }}</el-text>
                <div class="feedback-preview" v-if="row.feedbackInfo && row.feedbackInfo.length > 50">
                  <el-tooltip :content="row.feedbackInfo" placement="top">
                    <el-icon class="preview-icon"><InfoFilled /></el-icon>
                  </el-tooltip>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="创建时间" width="180" align="center">
            <template #default="{ row }">
              <div class="time-display">
                <span class="relative-time" :title="formatDateTime(row.createTime)">
                  {{ formatRelativeTime(row.createTime) }}
                </span>
                <div class="exact-time">{{ formatDateTime(row.createTime) }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="updateTime" label="修改时间" width="180" align="center">
            <template #default="{ row }">
              <div class="time-display">
                <span class="relative-time" :title="formatDateTime(row.updateTime)">
                  {{ formatRelativeTime(row.updateTime) }}
                </span>
                <div class="exact-time">{{ formatDateTime(row.updateTime) }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="120" align="center" fixed="right">
            <template #default="{ row }">
              <div class="operation-buttons">
                <el-button type="primary" size="small" :icon="View" @click="handleView(row)">
                  查看
                </el-button>
                <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[5, 10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 反馈详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="反馈详情"
      width="700px"
      :close-on-click-modal="false"
    >
      <div v-if="currentFeedback" class="feedback-detail">
        <div class="detail-header">
          <div class="header-info">
            <h3>{{ currentFeedback.sname }} 的反馈</h3>
            <p class="activity-info">活动：{{ currentFeedback.aname }}</p>
          </div>
          <div class="feedback-badge">
            <el-tag type="success" size="large">反馈详情</el-tag>
          </div>
        </div>
        
        <div class="detail-grid">
          <div class="detail-item">
            <label>反馈学生：</label>
            <span>{{ currentFeedback.sname }}</span>
          </div>
          <div class="detail-item">
            <label>活动名称：</label>
            <span>{{ currentFeedback.aname }}</span>
          </div>
          <div class="detail-item">
            <label>发布人：</label>
            <span>{{ currentFeedback.ename }}</span>
          </div>
          <div class="detail-item">
            <label>创建时间：</label>
            <span>{{ formatDateTime(currentFeedback.createTime) }}</span>
          </div>
          <div class="detail-item">
            <label>修改时间：</label>
            <span>{{ formatDateTime(currentFeedback.updateTime) }}</span>
          </div>
        </div>
        
        <div class="detail-item full-width">
          <label>反馈内容：</label>
          <div class="feedback-content-detail">
            {{ currentFeedback.feedbackInfo }}
          </div>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  View,
  Delete,
  User,
  Calendar,
  InfoFilled
} from '@element-plus/icons-vue'
import { queryFeedbackList, findFeedback, deleteFeedback } from '@/api/school'

// 响应式数据
const loading = ref(false)
const feedbackList = ref([])
const viewDialogVisible = ref(false)
const currentFeedback = ref(null)

// 表格高度计算
const tableHeight = computed(() => {
  return 'calc(100vh - 450px)'
})

// 搜索表单
const searchForm = reactive({
  sname: '',
  aname: '',
  feedbackInfo: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  limit: 5,
  total: 0
})


// 获取反馈列表
const getFeedbackList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      sname: searchForm.sname || undefined,
      aname: searchForm.aname || undefined,
      feedbackInfo: searchForm.feedbackInfo || undefined
    }
    
    const response = await queryFeedbackList(params)
    if (response && response.code === 0) {
      feedbackList.value = response.data || []
      pagination.total = response.count || 0
    }
  } catch (error) {
    console.error('获取反馈列表失败:', error)
    ElMessage.error('获取反馈列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getFeedbackList()
}

// 重置搜索
const handleReset = () => {
  searchForm.sname = ''
  searchForm.aname = ''
  searchForm.feedbackInfo = ''
  pagination.page = 1
  getFeedbackList()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.limit = size
  pagination.page = 1
  getFeedbackList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.page = page
  getFeedbackList()
}

// 查看反馈详情
const handleView = async (row) => {
  try {
    const response = await findFeedback(row.id)
    if (response && response.code === 0) {
      currentFeedback.value = response.data
      viewDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取反馈详情失败:', error)
    ElMessage.error('获取反馈详情失败')
  }
}


// 删除反馈
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除来自"${row.sname}"的反馈吗？此操作不可恢复！`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await deleteFeedback(row.id)
      if (response && response.code === 0) {
        ElMessage.success('删除成功')
        getFeedbackList()
      }
    } catch (error) {
      console.error('删除反馈失败:', error)
      ElMessage.error('删除反馈失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}


// 格式化日期时间显示
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  
  try {
    const date = new Date(dateTimeStr)
    if (isNaN(date.getTime())) return dateTimeStr
    
    const now = new Date()
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    
    // 如果是今年，不显示年份
    if (year === now.getFullYear()) {
      return `${month}-${day} ${hours}:${minutes}`
    }
    
    return `${year}-${month}-${day} ${hours}:${minutes}`
  } catch (error) {
    console.error('时间格式化错误:', error)
    return dateTimeStr
  }
}

// 格式化相对时间显示
const formatRelativeTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  
  try {
    const date = new Date(dateTimeStr)
    if (isNaN(date.getTime())) return dateTimeStr
    
    const now = new Date()
    const diffMs = now.getTime() - date.getTime()
    const diffSeconds = Math.floor(diffMs / 1000)
    const diffMinutes = Math.floor(diffSeconds / 60)
    const diffHours = Math.floor(diffMinutes / 60)
    
    // 未来时间显示为具体时间
    if (diffMs < 0) {
      return '未来时间'
    }
    
    // 今天的时间
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    const dateOnly = new Date(date)
    dateOnly.setHours(0, 0, 0, 0)
    const daysDiff = Math.floor((today.getTime() - dateOnly.getTime()) / (1000 * 60 * 60 * 24))
    
    // 相对时间显示
    if (daysDiff === 0) {
      // 今天
      if (diffSeconds < 60) {
        return '刚刚'
      } else if (diffMinutes < 60) {
        return `${diffMinutes}分钟前`
      } else {
        return `${diffHours}小时前`
      }
    } else if (daysDiff === 1) {
      return '昨天'
    } else if (daysDiff === 2) {
      return '前天'
    } else if (daysDiff < 7) {
      return `${daysDiff}天前`
    } else if (daysDiff < 30) {
      const weeks = Math.floor(daysDiff / 7)
      return `${weeks}周前`
    } else if (daysDiff < 365) {
      const months = Math.floor(daysDiff / 30)
      return `${months}个月前`
    } else {
      const years = Math.floor(daysDiff / 365)
      return `${years}年前`
    }
  } catch (error) {
    console.error('相对时间格式化错误:', error)
    return formatDateTime(dateTimeStr)
  }
}

// 页面加载时获取数据
onMounted(() => {
  getFeedbackList()
})
</script>

<style scoped>
.feedback-manage {
  padding: 5px 20px 20px 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow-y: auto;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;
  
  /* 自定义滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
}

/* Webkit浏览器滚动条样式 */
.feedback-manage::-webkit-scrollbar {
  width: 8px;
}

.feedback-manage::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.feedback-manage::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.feedback-manage::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}

.page-header {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  padding: 20px 0;
  border-bottom: 2px solid #e4e7ed;
}

.header-content h2 {
  margin: 0 0 4px 0;
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  background: linear-gradient(135deg, #409eff, #67c23a);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.header-desc {
  margin: 0;
  font-size: 14px;
  color: #909399;
  font-weight: 400;
}

.header-stats {
  display: flex;
  align-items: center;
}

.search-card {
  margin-bottom: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.search-card:hover {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
}

.table-card {
  background-color: #fff;
  margin-bottom: 10px;
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.table-wrapper {
  flex: 1;
  overflow: hidden;
}

/* 表格内容样式 */
.student-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.name-icon {
  color: #409eff;
  font-size: 16px;
}

.name-text {
  font-weight: 600;
}

.activity-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.activity-icon {
  color: #67c23a;
  font-size: 16px;
}

.activity-text {
  font-weight: 500;
}

.feedback-content {
  max-width: 250px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.feedback-text {
  line-height: 1.4;
  color: #606266;
  flex: 1;
}

.feedback-preview {
  flex-shrink: 0;
}

.preview-icon {
  color: #909399;
  font-size: 14px;
  cursor: pointer;
  transition: color 0.3s ease;
}

.preview-icon:hover {
  color: #409eff;
}

/* 操作按钮样式 */
.operation-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

:deep(.operation-buttons .el-button) {
  margin: 0 !important;
  min-width: 60px;
  height: 34px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  border-radius: 8px;
  font-weight: 500;
  font-size: 13px;
}

:deep(.operation-buttons .el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

:deep(.operation-buttons .el-button:active) {
  transform: translateY(0);
}

/* 特定按钮颜色优化 */
:deep(.operation-buttons .el-button--primary) {
  background: linear-gradient(135deg, #409eff, #66b1ff);
  border: none;
}

:deep(.operation-buttons .el-button--danger) {
  background: linear-gradient(135deg, #f56c6c, #f78989);
  border: none;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 16px;
  margin-bottom: 10px;
  padding: 16px 20px;
  flex-shrink: 0;
  background-color: #fff;
  border-top: 1px solid #ebeef5;
}

/* 反馈详情样式 */
.feedback-detail {
  padding: 16px 0;
}

.detail-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.feedback-badge {
  flex-shrink: 0;
}

.header-info h3 {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.activity-info {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 24px;
}

.detail-item {
  display: flex;
  align-items: flex-start;
}

.detail-item.full-width {
  grid-column: 1 / -1;
  flex-direction: column;
}

.detail-item label {
  font-weight: 600;
  color: #606266;
  min-width: 80px;
  margin-right: 12px;
}

.detail-item.full-width label {
  margin-bottom: 8px;
}

.feedback-content-detail {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 8px;
  line-height: 1.6;
  white-space: pre-wrap;
  color: #303133;
  border-left: 4px solid #409eff;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 空状态样式优化 */
:deep(.el-table__empty-block) {
  padding: 60px 0;
}

:deep(.el-table__empty-text) {
  color: #909399;
  font-size: 16px;
}

/* 加载状态优化 */
:deep(.el-loading-mask) {
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(2px);
}

:deep(.el-table th) {
  background: linear-gradient(135deg, #f5f7fa, #eef1f6);
  color: #303133;
  font-weight: 700;
  font-size: 14px;
  border-bottom: 2px solid #e4e7ed;
}

:deep(.el-table td) {
  padding: 16px 0;
  border-bottom: 1px solid #f0f2f5;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f8f9fa;
}

:deep(.el-table .el-table__row) {
  transition: background-color 0.3s ease;
}

/* 时间显示样式 */
.time-display {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.relative-time {
  font-weight: 500;
  color: #409eff;
  font-size: 13px;
  cursor: help;
}

.exact-time {
  font-size: 11px;
  color: #909399;
  line-height: 1.2;
}

/* 响应式优化 */
@media screen and (max-width: 768px) {
  .feedback-manage {
    padding: 5px 15px 5px 15px;
    max-height: calc(100vh - 50px);
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
    padding: 16px 0;
  }
  
  .header-content h2 {
    font-size: 24px;
  }
  
  .pagination-container {
    justify-content: center;
    margin-bottom: 8px;
    padding: 12px 15px;
  }
  
  .detail-grid {
    grid-template-columns: 1fr;
  }
  
  .time-display {
    gap: 1px;
  }
  
  .relative-time {
    font-size: 12px;
  }
  
  .exact-time {
    font-size: 10px;
  }
  
  /* 移动端操作按钮优化 */
  .operation-buttons {
    gap: 8px;
  }
  
  :deep(.operation-buttons .el-button) {
    min-width: 55px !important;
    height: 30px !important;
    font-size: 12px !important;
  }
  
  .feedback-content {
    max-width: 180px;
  }
}
</style>
